package com.jwaoo.mobile.view.user.model;

import android.content.Context;

import com.dx.as.common.ILoadListener;
import com.dx.as.db.IDBListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jwaoo.chat.Message;
import com.jwaoo.chat.UserInfo;
import com.jwaoo.chat.activity.module.db.DbService;
import com.jwaoo.chat.activity.module.fromapp.AppInstance;
import com.jwaoo.chat.data.db.ChatDatabase;

import java.util.List;

import http.IHttpListener;

/**
 * Created by jwaoo on 2018/1/15.
 */

public class UserModel extends IHttpListener{

    public UserModel(Context context, ILoadListener loadListener) {
        super(context, loadListener);
    }
    public void getContactInfo(final int uuid){
        DbService.getUserInfo(context,new IDBListener<ChatDatabase>() {
            @Override
            public void onOption(ChatDatabase database) {
                UserInfo userInfo = database.dbMsgDao().queryUserInfo(uuid);
                if (userInfo != null){
                    loadListener.onResponse(userInfo,0);
                }
                AppInstance.getInstance().getContactAsy(UserModel.this,uuid);
            }
        });
    }

    public void getSendFailedMessage(final int code ,final int uuid){
        DbService.getSendFailedMessages(context, new IDBListener<ChatDatabase>(){
            @Override
            public void onOption(ChatDatabase database) {
                List<Message> list = database.dbMsgDao().querySendFailedMessages(uuid);
                loadListener.onResponse(list,code);
            }
        });
    }

    @Override
    public void onResponse(Object response, int flg) {
        if (response != null){
            Gson gson = new Gson();
            String result = gson.toJson(response);
            final UserInfo userInfo = gson.fromJson(result,new TypeToken<UserInfo>(){}.getType());
            this.loadListener.onResponse(userInfo,flg);
            if (userInfo != null){
                DbService.getUserInfo(context, new IDBListener<ChatDatabase>(){
                    @Override
                    public void onOption(ChatDatabase database) {
                        UserInfo info = database.dbMsgDao().queryUserInfo(userInfo.getId());
                        if (info != null) database.dbMsgDao().updateUserInfo(userInfo);
                        else database.dbMsgDao().insertUserInfo(userInfo);
                    }
                });
            }
        }
    }

    @Override
    public void onFailure(Throwable t) {
        this.loadListener.onFailure(t);
    }
}
